const winston = require('winston');
const { combine, timestamp, printf } = winston.format;

const logFormat = printf(({ level, message, timestamp }) => {
    return `${timestamp} [${level}]: ${message}`;
});

const logger = winston.createLogger({
    level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
    format: combine(
        timestamp(),
        logFormat
    ),
    transports: [
        new winston.transports.Console(),
        new winston.transports.File({ filename: 'logs/combined.log' })
    ]
});

const requestLogger = (req, res, next) => {
    const startTime = Date.now();
    const { method, originalUrl, body, query, headers, ip } = req;

    logger.info({
        message: `Incoming ${method} Request to ${originalUrl} from ${ip}`,
        method,
        path: originalUrl,
        query,
        body: process.env.NODE_ENV === 'development' ? body : undefined,
        headers: process.env.NODE_ENV === 'development' ? headers : undefined,
        ip,
        userAgent: headers?.['user-agent'],
        timestamp: new Date().toISOString()
    });

    const oldSend = res.send;
    res.send = function (data) {
        const responseTime = Date.now() - startTime;

        logger.info({
            message: `Outgoing Response for ${originalUrl} - Status: ${res.statusCode}, Time: ${responseTime}ms, Size: ${res.get('Content-Length') || 0} bytes`,
            statusCode: res.statusCode,
            path: originalUrl,
            responseTime: `${responseTime}ms`,
            contentLength: res.get('Content-Length') || 0,
            timestamp: new Date().toISOString()
        });

        oldSend.apply(res, arguments);
    };

    next();
};

module.exports = {
    logger,
    requestLogger
};